import { PayloadAction, createSlice } from '@reduxjs/toolkit';
import { initStates, State } from './initState';
import * as reducers from './reducer';
import { login, getUserInfo } from './asyncThunk';
import { IUserInfo } from 'src/interface';

const userStore = createSlice({
  name: 'user',
  initialState: initStates,
  reducers,
  extraReducers: (build) => {
    build
      .addCase(login.fulfilled, (state, action: PayloadAction<string>) => {
        state.token = action.payload;
      })
      .addCase(getUserInfo.pending, (state) => {
        state.loading = true;
      })
      .addCase(getUserInfo.fulfilled, (state, action: PayloadAction<IUserInfo | null>) => {
        if (!action.payload) return;
        state.user = action.payload;
        state.loading = false;
      })
      .addCase(getUserInfo.rejected, (state) => {
        state.loading = false;
      });
  },
});

export const { loginSuccess, setUserToken, logout } = userStore.actions;
export type UserState = State;
export { login, getUserInfo };
export default userStore.reducer;
